var util = require('../../utils/util.js')
var app = getApp();
Page({   

  /**
   * 页面的初始数据
   */
  data: {
    store_cart_list: [],
    address_info: {}, //地址信息
    content: [],
    all_count: 0,
    sum: 0, //实付价格
    order_price: 0, //没算上优惠券的价格
    address_id: null,
    pay_name: "online", //支付方式 在线支付 货到付款 门店支付 'online', 'offline', 'chain'
    cart_id: "",
    show_window: false,
    rpt_list: [],
    freight_hash: "",
    sp_rpt: "",
    order_amount: "", //商品总价
    has_md: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.address_info = "";
    console.log(options);
    that.setData({
      cart_id: options.cart_id,
    })
    util.postUrl('buy/buy_step1', {
      cart_id: options.cart_id,
    }, function(res) {
      console.log(res);
      var store_cart_list = res.data.datas.store_cart_list;
      if (Object.keys(store_cart_list).length == 1) {
        that.setData({
          has_md: true
        })
      } else {
        that.setData({
          has_md: false
        })
      }

      var content = res.data.datas.address_api.content;
      var all_count = 0;
      var sum = parseFloat(res.data.datas.order_amount);
      if (res.data.datas.address_id) {
        for (var key in store_cart_list) {
          store_cart_list[key].fee = content[key];
          sum = sum + parseFloat(store_cart_list[key].fee);
          all_count = all_count + store_cart_list[key].store_goods_num_total;
        }
      } else {
        for (var key in store_cart_list) {
          store_cart_list[key].fee = 0;
          sum = sum + parseFloat(store_cart_list[key].fee);
          all_count = all_count + store_cart_list[key].store_goods_num_total;
        }
      }
      console.log(store_cart_list);
      that.setData({
        store_cart_list: store_cart_list,
        address_info: res.data.datas.address_info,
        content: content,
        all_count: all_count,
        sum: sum,
        order_price: sum,
        order_amount: res.data.datas.order_amount,
        address_id: res.data.datas.address_id,
        freight_hash: res.data.datas.freight_hash,
        rpt_list: res.data.datas.rpt_list,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (app.address_info != "") {

      this.setData({
        address_info: app.address_info,
        address_id: app.address_info.address_id,
      })
      util.postUrl("buy/change_address", {
        address_id: that.data.address_info.address_id,
        freight_hash: that.data.freight_hash

      }, function(res) {
        console.log(res);
        var store_cart_list = that.data.store_cart_list;
        var content = res.data.datas.content;
        var sum = parseFloat(that.data.order_amount);
        console.log("订单价格1", sum);
        for (var key in store_cart_list) {
          console.log(key, store_cart_list[key].fee);
          store_cart_list[key].fee = content[key];
          sum = sum + parseFloat(content[key]);
        }

        console.log("订单价格2", sum);
        that.setData({
          store_cart_list: store_cart_list,
          order_price: sum,
        })
        var del_p = 0;
        // var rpt_list = that.data.rpt_list;
        // for (var i = 0; i < rpt_list.length; i++) {
        //   if (rpt_list[i].check) {
        //     del_p = rpt_list[i].rpacket_price;
        //   }
        //   break;
        // }
        if (that.data.sp_rpt != "") {
          del_p = that.data.sp_rpt.rpacket_price;
        }
        sum = sum - del_p;
        that.setData({
          sum: sum.toFixed(2),
        })

      })
    }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  goShopMa: function() {
    wx.navigateTo({
      url: '../shopManagement/shopManagement?flag=1',
    })
  },
  change_pay_type: function(e) {
    this.setData({
      pay_name: e.currentTarget.dataset.pay,
    })

  },
  submit: function() {
    var that = this;
    var sp_rpt = this.data.sp_rpt;

    if (!that.data.address_id) {
      wx.showToast({
        title: "请选择门店地址",
      })
      return;  
    }
    var pay_name = that.data.pay_name;

    util.postUrl('buy/buy_step2', {
      pay_name: that.data.pay_name,
      cart_id: that.data.cart_id,
      address_id: that.data.address_id,
      rpt: JSON.stringify(sp_rpt),
    }, function(res) {
      if (res.data.code == 400) {
        wx.showToast({
          title: res.data.datas.error,
          icon: 'none'
        })
        return;
      }
      var order_check = wx.getStorageSync('order_check');
      var check_list = wx.getStorageSync('check_list');
      if (order_check) {
        for (var i = 0; i < order_check.length; i++) {
          check_list.splice(check_list.indexOf(order_check[i]), 1);
        }
      }
      wx.setStorageSync('check_list', check_list);
      var pay_sn = res.data.datas.pay_sn;

      if (pay_name == 'offline') {
        wx.redirectTo({
          url: '../buy_finish/buy_finish?sum=' + that.data.sum + "&address_info=",
        })
        return;
      }
      if (pay_name == 'chain') {
        wx.showModal({
          title: '提示',
          content: '确认工作人员在附近',
          success: function(res) {
            if (res.confirm) {
              util.postUrl("buy/prepay_id", {
                pay_sn: pay_sn,
                open_id: wx.getStorageSync("open_id")
              }, function(res) {
                if (res) {  
                  console.log("buy/prepay_id", res);
                  wx.requestPayment({
                    'timeStamp': res.data.datas.pay_info.timeStamp + "",
                    'nonceStr': res.data.datas.pay_info.nonceStr,
                    'package': res.data.datas.pay_info.package,
                    'signType': 'MD5',
                    'paySign': res.data.datas.pay_info.paySign,
                    'success': function(res) {
                      console.log("支付=", res);
                      wx.redirectTo({
                        url: '../buy_finish/buy_finish?sum=' + that.data.sum + "&address_info=" + JSON.stringify(that.data.address_info),
                      })
                    },
                    'fail': function(res) {

                      wx.redirectTo({
                        url: '../myOrder/myOrder?currentTab=1',
                      })

                    }
                  })

                } else {
                  wx.showToast({
                    title: res.data.datas.error,
                    icon: 'none',
                  })
                }
              })
            }
          }
        })
        return;
      }
      util.postUrl("buy/prepay_id", {
        pay_sn: pay_sn,
        open_id: wx.getStorageSync("open_id")
      }, function(res) {
        if (res) {
          console.log("buy/prepay_id", res);
          wx.requestPayment({
            'timeStamp': res.data.datas.pay_info.timeStamp + "",
            'nonceStr': res.data.datas.pay_info.nonceStr,
            'package': res.data.datas.pay_info.package,
            'signType': 'MD5',
            'paySign': res.data.datas.pay_info.paySign,
            'success': function(res) {
              console.log("支付=", res);
              wx.redirectTo({
                url: '../buy_finish/buy_finish?sum=' + that.data.sum + "&address_info=" + JSON.stringify(that.data.address_info),
              })
            },
            'fail': function(res) {
              wx.redirectTo({
                url: '../myOrder/myOrder?currentTab=1',
              })

            }
          })

        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none',
          })
        }
      })
    })


  },
  showWindow: function() {
    this.setData({
      show_window: !this.data.show_window,
    })
  },
  closeWindow: function() {
    this.setData({
      show_window: false,
    })
  },
  userRpt: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var rpt_list = this.data.rpt_list;
    var temp = rpt_list[index];
    var del_p = 0;
    if (temp.check) {
      temp.check = false;
      this.setData({
        rpt_list: rpt_list,
        sp_rpt: "",
      })

    } else {
      for (var i = 0; i < rpt_list.length; i++) {
        rpt_list[i].check = false;
      }
      temp.check = true;
      this.setData({
        rpt_list: rpt_list,
        sp_rpt: temp,
      })
      del_p = temp.rpacket_price;
    }
    var sum = that.data.order_price - del_p;
    that.setData({
      sum: sum.toFixed(2),
    })

  }
})